
import PKwebsocket from "@/lolo/Ws";
import eventBus from "@/lolo/eventBus";

let lastTouchEnd = 0; //更新手指弹起的时间
document.addEventListener("touchstart", function (event) {
  //多根手指同时按下屏幕，禁止默认行为
  if (event.touches.length > 1) {
    event.preventDefault();
  }
}, false);

document.addEventListener(
  "touchend",
  function (event) {
    let now = new Date().getTime();
    if (now - lastTouchEnd <= 300) {
      //当两次手指弹起的时间小于300毫秒，认为双击屏幕行为
      event.preventDefault();
    } else {
      // 否则重新手指弹起的时间
      lastTouchEnd = now;
    }
  },
  { passive: false }
);

//阻止双指放大页面
document.addEventListener("gesturestart", function (event) {
  event.preventDefault();
});
document.oncontextmenu = function (e) {
  e.preventDefault()
}
let deferredPrompt: any;
window.addEventListener('beforeinstallprompt', (e) => {
  e.preventDefault();
  deferredPrompt = e;
  // 显示安装按钮
});
// 在用户点击安装按钮时调用
window.addEventListener('click', () => {
  const appinstall_popup = sessionStorage.getItem('appinstall_popup')
  if (appinstall_popup || !deferredPrompt) return
  deferredPrompt.prompt();
  deferredPrompt.userChoice.then((_choiceResult: any) => {
    // if (choiceResult.outcome === 'accepted') {
    //   console.log('User accepted the install prompt');
    // } else {
    //   console.log('User dismissed the install prompt');
    // }
    sessionStorage.setItem('appinstall_popup', '1')
    deferredPrompt = null;
  });
});

// if ('serviceWorker' in navigator) {
//   navigator.serviceWorker.register('/service-worker.js')
//     .then((registration) => {
//       console.log('Service Worker registered with scope:', registration.scope);
//     })
//     .catch((error) => {
//       console.log('Service Worker registration failed:', error);
//     });
// }
// window.addEventListener('offline',function(){
//   alert('Please check if your network connection is normal')
// },true)

document.addEventListener("visibilitychange", async () => {
  if (document.visibilityState == "visible") {
    if (PKwebsocket.instance == null) {
      // window.location.reload();
    }
    console.log("进入前台");
    eventBus.emit('window_visible')
  }
  if (document.visibilityState == "hidden") {
    console.log("切换到后台")
  }
})


// let startX = 0, startY = 0;

// document.addEventListener('touchstart', (e) => {
//   startX = e.touches[0].clientX;
//   startY = e.touches[0].clientY;
// }, { passive: true });

// document.addEventListener('touchmove', (e) => {
//   const deltaX = e.touches[0].clientX - startX;
//   const deltaY = e.touches[0].clientY - startY;

//   // 确保事件可取消再调用 preventDefault()
//   if (e.cancelable && Math.abs(deltaX) > Math.abs(deltaY)) {
//     if (!window.location.href.includes('/deposit/explain')) {
//       e.preventDefault(); // 阻止默认行为（左右滑动切换路由）
//     }
//   }
// }, { passive: false });

// export const stopMove = () => {
//   if (window.scrollY > 0) {
//     window.scrollTo(0, 0); // 强制返回顶部
//   }
// }
// 影响正常滚动和页面抖动
// document.addEventListener('scroll', stopMove);
const vwo = window.innerWidth
function setFullHeight() {
  const vwn = window.innerWidth
  // const vhn = window.innerHeight
  let vh = window.visualViewport
  ? window.visualViewport.height * 0.01
  : window.innerHeight * 0.01;

  const localVh = localStorage.getItem('layout-vh')
  if (Math.abs(vwo - vwn) < 5 && localVh && localVh !== 'NaN') {
    vh = Number(localVh)  
  }
  document.documentElement.style.setProperty('--vh', `${vh}px`);
  localStorage.setItem('layout-vh', vh + '')

}

// 事件监听
// let debounceTimer: any;
// const handleResize = () => {
//   clearTimeout(debounceTimer);
//   debounceTimer = setTimeout(setStableVH, 300);
// };

// if ('visualViewport' in window) {
//   // @ts-ignore
//   window.visualViewport.addEventListener('resize', handleResize);
// } else {
//   // @ts-ignore
//   window.addEventListener('resize', handleResize);
// }

// window.addEventListener('scroll', () => {
//   const currentScroll = window.scrollY || document.documentElement.scrollTop;
  
//   // 记录最大下拉距离（弹性滚动时 scrollY 为负值）
//   if (currentScroll < 0) {
//     maxPullDownDistance = Math.max(maxPullDownDistance, Math.abs(currentScroll));
    
//     // 当超过阈值时强制更新
//     if (maxPullDownDistance > 50) {
//       requestAnimationFrame(() => {
//         setStableVH();
//       });
//     }
//   } else {
//     maxPullDownDistance = 0; // 重置计数器
//   }
// });

// // 滚动结束检测
// if ('onscrollend' in window) {
//   window.addEventListener('scrollend', () => {
//     setStableVH();
//   });
// } else {
//   let isTouching = false;
//   // @ts-ignore
//   window.addEventListener('touchstart', () => (isTouching = true));
//   // @ts-ignore
//   window.addEventListener('touchend', () => {
//     isTouching = false;
//     requestAnimationFrame(() => {
//       if (!isTouching && maxPullDownDistance > 30) { // 30px 容差值
//         setStableVH();
//       }
//       maxPullDownDistance = 0; // 重置状态
//     });
//   });
// }

// 初始加载触发
window.addEventListener('load', setFullHeight);
window.addEventListener('resize', setFullHeight);
